<template>
    <div>
        <searchData
                :search-data="searchArr"
                @search="search" />

        <a-card :bordered="false" style="overflow: auto">
            <div class="table-operator">
                <a-button
                        v-btn-permission="'pm_029_add_11'"
                        type="primary"
                        @click="handelAdd">
                    新增年度计划产值
                </a-button>
                <a-button
                        v-btn-permission="'pm_029_exp_15'"
                        type="primary"
                        @click="exportCorporateAnnualPlanVisible = true">
                    导出公司年度计划
                </a-button>
            </div>

            <list-table
                    ref="table"
                    bordered
                    size="default"
                    row-key="id"
                    :columns="columns"
                    :request="loadData"
                    :alert="true"
                    show-size-changer
                    show-quick-jumper
                    show-pagination="auto">
                <template slot="serial" slot-scope="text,record, index">
                    {{index+1}}
                </template>
                <template slot="version" slot-scope="text, record">
                    <a @click="lookVersion(record)">{{record.versionNumber}}</a>
                </template>
                <template slot="action" slot-scope="text, record">
                    <MoreButton>
                        <a @click="jump(record, 'look')" v-btn-permission="'pm_029_loo_10'">查看</a>
                        <template v-if="record.auditStatus==='DRAFT' || record.auditStatus==='REJECTED'">
                        <a @click="jump(record, 'edit')" v-btn-permission="'pm_029_edi_12'">编辑</a>
                        </template>
                        <template v-if="record.auditStatus==='PAST'">
                            <a @click="jump(record, 'change')" v-btn-permission="'pm_029_cha_13'">变更</a>
<!--                            <a>导出</a>-->
                        </template>
                        <template v-if="toNumber(record.versionNumber)>1 || record.auditStatus!=='DRAFT'">
                            <a @click="approvalLook(record)">审批信息</a>
                        </template>
                        <a v-if="record.auditStatus === 'PAST'" v-btn-permission="'pm_029_exp_14'" @click="handleExportCorporateAnnualPlanBranch(record)">导出</a>
                    </MoreButton>
                </template>
            </list-table>
            <ApprovalDetails
                    :title="'审批信息'"
                    :business-id="businessId"
                    :visible="visibleApprove"
                    @cancel="visibleApprove = false"
                    @confirm="visibleApprove = false"
            />
            <!-- 选择审批人 -->
        </a-card>
        <a-modal v-model="versionVisible" title="版本记录"  width="70%">
            <a-table
                    ref="tbs"
                    bordered
                    size="default"
                    row-key="id"
                    :loading="loadingS"
                    :pagination="false"
                    :data-source="dataSource"
                    :columns="columns2"
                   >
                <template slot="serial" slot-scope="text,record, index">
                    {{index+1}}
                </template>
                <template slot="action" slot-scope="text, record">
                    <div style="height: 34px;line-height: 34px">
                        <a @click="lookV(record)">查看详情</a>
                    </div>
                </template>
            </a-table>
            <div slot="footer">
                <a-button @click="versionVisible=false">关闭</a-button>
            </div>
        </a-modal>
        <!-- 导出公司年度计划模态框 -->
        <BaseModal
          :visible="exportCorporateAnnualPlanVisible"
          title="导出公司年度计划"
          width="40%"
          @cancel="handleExportCorporateAnnualPlanCancel"
        >
          <custom-form
            ref="corporateAnnualPlanForm"
            is-validate
            :edit-model="''"
            :form="corporateAnnualPlanForm"
            :form-list="corporateAnnualPlanFormOption"
            :rules="corporateAnnualPlanFormRules"
          />
          <template v-slot:footer>
            <a-button @click="handleExportCorporateAnnualPlanCancel">关闭</a-button>
            <a-button :loading="exportCorporateAnnualPlanLoading" type="primary" @click="handleExportCorporateAnnualPlan">导出</a-button>
          </template>
        </BaseModal>
        <!-- 导出公司年度计划模态框 -->
    </div>
</template>

<script>
  import BaseModal from '@/components/BaseModal'
  import {queryYearPlanList, queryYearVersionRecord, exportCompany, exportBranch} from "@/api/project/productionRecords"
  import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
  import OrgTreeSelect from '@/components/OrgTreeSelect'
  import ApprovalDetails from '@/components/approvalDetails'
  import moment from 'moment'

  const columns = [
    {
      title: '序号',
      width: 65,
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '年度',
      dataIndex: 'year'
    },
    {
      title: '分公司',
      dataIndex: 'branchComName'
    },
    {
      title: '年度计划产值（万元）',
      dataIndex: 'yearPlanOutput'
    },
    {
      title: '版本',
      dataIndex: 'versionNumber',
      scopedSlots: { customRender: 'version' }
    },
    {
      title: '状态',
      dataIndex: 'auditStatusName'
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '170px',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    name: 'a' + Date.now(),
    components: {
      ApprovalDetails,
      BaseModal
    },
    data() {
      return {
        versionVisible: false,
        loading: false,
        visibleApprove: false,

        columns,
        columns2: [
          {
            title: '序号',
            width: 65,
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '版本号',
            dataIndex: 'versionNumber'
          },
          {
            title: '年度计划产值（万元）',
            dataIndex: 'yearPlanOutput'
          },
          {
            title: '状态',
            dataIndex: 'auditStatusName'
          },
          {
            title: '版本创建时间',
            dataIndex: 'createTime'
          },
          {
            title: '创建人',
            dataIndex: 'creatorName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '170px',
            scopedSlots: { customRender: 'action' }
          },
        ],
        searchArr: [
          // 搜索框
          {
            name: '分公司',
            valueKey: 'branchComId',
            type: SelectSubCompany
          },
          {
            name: '年度',
            value: 'year',
            type: 'year',
            span: 8
          },
        ],

        businessId: '',
        queryParam: {},
        data: [],
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          return queryYearPlanList(requestParameters).then((res) => {
            res.data.forEach(item=>{
              item.year = moment(item.year).format("YYYY")
            })
            return res
          })
        },
        dataSource: [],
        loadingS: false,
        id: '',
        // 导出公司年度计划模态框显示隐藏
        exportCorporateAnnualPlanVisible: false,
        // 导出公司年度计划中
        exportCorporateAnnualPlanLoading: false,
        // 导出公司年度计划表单
        corporateAnnualPlanForm: {},
        // 导出公司年度计划表单校验
        corporateAnnualPlanFormRules: {
          year: [{ required: true, message: '请选择需要导出数据的年份', trigger: 'change' }]
        },
        // 导出公司年度计划表单项
        corporateAnnualPlanFormOption:[
          {
            label: '请选择需要导出数据的年份',
            keyName: 'year',
            type: 'a-date-picker',
            span: 12,
              attrs: {
              mode: 'year',
              format: 'YYYY',
              valueFormat: 'YYYY'
            }
          }
        ]
      }
    },

     activated() {
       this.$refs.table.refresh(true)
    },
    watch: {
      versionVisible(newVal) {
        if(newVal) {
         this.$nextTick(()=>{
           this.loadDataVersion()
         })
        } else {
          this.dataSource = []
        }
      },
      exportCorporateAnnualPlanVisible(val){
        if(val){
          this.$checkRequireItem()
        }
      }
    },
    computed: {},
    methods: {
      toNumber(num) {
        return num ? num.replace("V", ''): ''
      },
      loadDataVersion() {
        this.loadingS = true
         queryYearVersionRecord(this.id).then(res=>{
           this.loadingS = false
           this.dataSource = res.data
         })
      },
      lookVersion(row) {
        this.id = row.id
        this.versionVisible = true
      },
      selectOrg(val) {
        if (val.length > 1) {
          this.form.branchId = val[val.length - 2].orgId
          this.$set(this.form, 'projectNum', val[val.length - 1].projectCode)
        }
      },
      handleCancels() {
        this.visibles = false
      },
      search(val) {
        this.queryParam = {
          query: { ...val }
        }
        this.$refs.table.refresh(true)
      },

      handelAdd() {
        this.$router.push("/project/productionRecord/addPlannedOutputValue")
      },
      jump(row, pageType){
        this.$router.push({
          path: '/project/productionRecord/addPlannedOutputValue',
          query: {
            id: row.id,
            pageType,
            t: row.auditStatus,
              activeKey: this.$route.query.activeKey
          }
        })
      },
      //版本查看详情
      lookV(row) {
        this.versionVisible = false
        this.$router.push({
          path: '/project/productionRecord/addPlannedOutputValue',
          query: {
            id: this.id,
            pageType: 'look',
            versionNumber: row.versionNumber
          }
        })
      },
      approvalLook(row) {
        this.businessId = row.id;
        this.visibleApprove = true;
      },
      /**
       * @description: 选择审批人关闭回调时关闭提交弹窗
       * @return {void}
       */
      closeSelectApprover() {
        this.handleCancel()
        this.handleCancels()
        this.$refs.table.refresh(true)
      },
      /**
       * @description: 取消导出公司年度计划
       * @return {void}
       */      
      handleExportCorporateAnnualPlanCancel(){
        this.exportCorporateAnnualPlanVisible = false
        this.corporateAnnualPlanForm = {}
      },
      /**
       * @description: 导出公司年度计划
       * @return {void}
       */      
      handleExportCorporateAnnualPlan(){
        this.exportCorporateAnnualPlanLoading = true
        this.$refs.corporateAnnualPlanForm.validate((valid) => {
          if (valid) {
            exportCompany({year: moment(this.corporateAnnualPlanForm.year).format("YYYY")}).then(res=>{
              this.handleDownload(res)
              this.$message.success('导出成功')
              this.handleExportCorporateAnnualPlanCancel()
            }).finally(()=>{
              this.exportCorporateAnnualPlanLoading = false
            })
          }
        })
      },
      /**
       * @description: 下载
       * @return {void}
       */
      handleDownload(res) {
        const blob = new Blob([res.data])
        const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = filename // 获取文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放blob对象
      },
      /**
       * @description: 导出公司年度计划分公司
       * @param {object} record 行数据
       * @return {void}
       */      
      handleExportCorporateAnnualPlanBranch(record){
        exportBranch({id: record.id}).then(res=>{
          this.handleDownload(res)
          this.$message.success('导出成功')
        })
      }
    }
  }
</script>


